package com.nutransit;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mylibrary.mylibrary.imageloader.ImageLoader;
import com.mylibrary.mylibrary.parsing.AsyncTaskFileUploadUtility;
import com.mylibrary.mylibrary.parsing.AsyncTaskInterface;
import com.mylibrary.mylibrary.parsing.AsyncTaskUtility;
import com.mylibrary.mylibrary.util.CommonCode;
import com.mylibrary.mylibrary.util.SessionData;
import com.nutransit.commoncode.MySpinnerAdapter;
import com.nutransit.commoncode.Webservice_parametrs;

public class Fragment_Update_Profile extends Fragment implements OnClickListener, Webservice_parametrs
{
	private Context context;
	private Resources resources;
	private ImageLoader imageLoader;
	private SessionData sessionData;
	
	private TextView tv_USER_DETAILS, tv_Sharing_Rewards;
	private ImageView iv_Profile_Pict;
	private Button btn_Update_Profile;
	private LinearLayout  lLayout_Sharing_Reward_Bottom,lLayout_Account_Details_Bottom, lLayout_Address;
	private EditText et_FIRST_NAME, et_LAST_NAME, et_PHONE_NUMBER, et_ADDRESS,et_CITY, et_ZIP_CODE, et_USER_NAME, et_EMAIL_ADDRESS, et_PASSWORD, et_TLC_NUMBER; 
	private Spinner spn_COUNTRY, spn_STATE, spn_BASE_NAME, spn_DRIVER_TYPE;
	private View rootView;
	
	private MySpinnerAdapter mySpinnerAdapter_Country, mySpinnerAdapter_Base; 
	
	private String str_FIRST_NAME, str_LAST_NAME, str_PHONE_NUMBER, str_ADDRESS,str_CITY, str_ZIP_CODE, str_USER_NAME, str_EMAIL_ADDRESS,
		str_PASSWORD, str_BASE_NAME, str_DRIVER_TYPE, str_TLC_NUMBER, strCountry_id = null, strStateId = null, imageFilePath = null,
				str_user_Country_id, str_user_State_id;
	private final int SELECT_FILE = 123;
	private HashMap<String, String> hashMap;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		rootView = inflater.inflate(R.layout.activity_user_profile, container, false);
		
		init_var();
		return rootView;
	}

	private void init_var()
	{
		context = getActivity();
		resources = context.getResources();
		imageLoader = new ImageLoader(context);
		sessionData = new SessionData(context, PACKAGE_NAME);
		
		et_FIRST_NAME = (EditText) rootView.findViewById(R.id.et_FIRST_NAME); 
		et_LAST_NAME = (EditText) rootView.findViewById(R.id.et_LAST_NAME); 
		et_PHONE_NUMBER = (EditText) rootView.findViewById(R.id.et_PHONE_NUMBER);
		et_ADDRESS = (EditText) rootView.findViewById(R.id.et_ADDRESS);
		et_CITY = (EditText) rootView.findViewById(R.id.et_CITY);
		et_ZIP_CODE = (EditText) rootView.findViewById(R.id.et_ZIP_CODE);
		et_USER_NAME = (EditText) rootView.findViewById(R.id.et_USER_NAME);
		et_EMAIL_ADDRESS = (EditText) rootView.findViewById(R.id.et_EMAIL_ADDRESS);
		et_PASSWORD = (EditText) rootView.findViewById(R.id.et_PASSWORD);
		et_TLC_NUMBER = (EditText) rootView.findViewById(R.id.et_TLC_NUMBER);
		
		spn_COUNTRY = (Spinner) rootView.findViewById(R.id.spn_COUNTRY);
		spn_STATE = (Spinner) rootView.findViewById(R.id.spn_STATE);
		spn_BASE_NAME = (Spinner) rootView.findViewById(R.id.spn_BASE_NAME);
		spn_DRIVER_TYPE = (Spinner) rootView.findViewById(R.id.spn_DRIVER_TYPE);
		
		tv_USER_DETAILS = (TextView) rootView.findViewById(R.id.tv_USER_DETAILS);
		tv_Sharing_Rewards = (TextView) rootView.findViewById(R.id.tv_Sharing_Rewards);
		
		iv_Profile_Pict = (ImageView) rootView.findViewById(R.id.iv_Profile_Pict);
		
		btn_Update_Profile = (Button) rootView.findViewById(R.id.btn_Update_Profile);
		btn_Update_Profile.setOnClickListener(this);
		
		lLayout_Sharing_Reward_Bottom = (LinearLayout) rootView.findViewById(R.id.lLayout_Sharing_Reward_Bottom);
		lLayout_Account_Details_Bottom = (LinearLayout) rootView.findViewById(R.id.lLayout_Account_Details_Bottom);
		lLayout_Address = (LinearLayout) rootView.findViewById(R.id.lLayout_Address);
		
		(rootView.findViewById(R.id.fLayout_Profile_Pict)).setOnClickListener(this);
		
		if(MainActivity_Nutransit.strUserType.equalsIgnoreCase(TAG_user))
		{
			tv_USER_DETAILS.setText(resources.getString(R.string.USER_DETAILS));
			tv_Sharing_Rewards.setText(resources.getString(R.string.SHARING_REWARDS));
			lLayout_Sharing_Reward_Bottom.setVisibility(View.VISIBLE);
			lLayout_Account_Details_Bottom.setVisibility(View.GONE);
			lLayout_Address.setVisibility(View.GONE);
		}
		else
		{
			tv_USER_DETAILS.setText(resources.getString(R.string.DRIVER_DETAILS));
			tv_Sharing_Rewards.setText(resources.getString(R.string.ACCOUNT_DETAILS));
			lLayout_Sharing_Reward_Bottom.setVisibility(View.GONE);
			lLayout_Account_Details_Bottom.setVisibility(View.VISIBLE);
			lLayout_Address.setVisibility(View.VISIBLE);
		}
		
		set_user_data();
		if(!MainActivity_Nutransit.strUserType.equalsIgnoreCase(TAG_user))
			get_Country_State();
		
	}

	private void set_user_data()
	{
		try
		{
			JSONObject jsonObject = MainActivity_Nutransit.jsonObject_data;
			et_FIRST_NAME.setText(jsonObject.has(TAG_first_name)?jsonObject.getString(TAG_first_name):"");
			et_LAST_NAME.setText(jsonObject.has(TAG_last_name)?jsonObject.getString(TAG_last_name):"");
			et_PHONE_NUMBER.setText(jsonObject.has(TAG_phone)?jsonObject.getString(TAG_phone):"");
			et_ADDRESS.setText(jsonObject.has(TAG_address)?jsonObject.getString(TAG_address):"");
			et_CITY.setText(jsonObject.has(TAG_city)?jsonObject.getString(TAG_city):"");
			et_ZIP_CODE.setText(jsonObject.has(TAG_zip)?jsonObject.getString(TAG_zip):"");
			et_USER_NAME.setText(jsonObject.has(TAG_username)?jsonObject.getString(TAG_username):"");
			et_EMAIL_ADDRESS.setText(jsonObject.has(TAG_email)?jsonObject.getString(TAG_email):""); 
			et_PASSWORD.setText(jsonObject.has(TAG_password)?jsonObject.getString(TAG_password):"");
			et_TLC_NUMBER.setText(jsonObject.has(TAG_tlc)?jsonObject.getString(TAG_tlc):"");
			if(jsonObject.has(TAG_image))
			{
				String strImage = jsonObject.getString(TAG_image);
				if(strImage!=null && strImage.length()>0)
						imageLoader.DisplayImage(URL_IMAGE_URL+strImage, iv_Profile_Pict);
			}
			if(jsonObject.has(TAG_driver_type))
			{
				String strDriverType = jsonObject.getString(TAG_driver_type);
				if(strDriverType!=null)
				{
					if(strDriverType.equalsIgnoreCase("c"))
						spn_DRIVER_TYPE.setSelection(1);
					else if(strDriverType.equalsIgnoreCase("v"))
						spn_DRIVER_TYPE.setSelection(2);
				}
			}
			if(jsonObject.has(TAG_country_id))
			{
				str_user_Country_id = jsonObject.getString(TAG_country_id);
				str_user_State_id = jsonObject.getString(TAG_state_id);
			}
		}
		catch(JSONException e)
		{
			e.printStackTrace();
		}
	}

	private void get_Country_State()
	{
		new AsyncTaskUtility(context, null, URL_GET_COUNTRY_STATE).getJSONResponse(new AsyncTaskInterface()
		{
			@Override
			public void getJSONObjectFromAsynkTask(JSONObject json)
			{
				try
				{
					JSONArray  jsonArray_Country = json.getJSONArray(TAG_country);
					final JSONArray  jsonArray_State = json.getJSONArray(TAG_state);
					final JSONArray  jsonArray_Base = json.getJSONArray(TAG_base);
					if(jsonArray_Country!=null)
					{
						mySpinnerAdapter_Country = new MySpinnerAdapter(context, jsonArray_Country);
						spn_COUNTRY.setAdapter(mySpinnerAdapter_Country);
						set_State_Spinner_position(spn_COUNTRY, str_user_Country_id);
						spn_COUNTRY.setOnItemSelectedListener(new OnItemSelectedListener()
						{
							@Override
							public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
							{
								try
								{
									strCountry_id = ((TextView)view.findViewById(R.id.tv_id)).getText().toString().trim();
									JSONArray jsonArray = new JSONArray();
									for (int i = 0; i < jsonArray_State.length(); i++)
									{
										if(jsonArray_State.getJSONObject(i).getString(TAG_country_id).equalsIgnoreCase(strCountry_id))
										{
											jsonArray.put(jsonArray_State.getJSONObject(i));
										}
									}
									set_State_Spinner_Value(jsonArray, spn_STATE, context);
									set_State_Spinner_position(spn_STATE, str_user_State_id);
								}
								catch(JSONException e)
								{
									e.printStackTrace();
								}
							}
							@Override public void onNothingSelected(AdapterView<?> parent) { }
						});
						spn_STATE.setOnItemSelectedListener(new OnItemSelectedListener()
						{
							@Override
							public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
							{
								strStateId = ((TextView)view.findViewById(R.id.tv_id)).getText().toString().trim();
							}
							@Override public void onNothingSelected(AdapterView<?> parent) { }
						});
					}
					
					if(jsonArray_Base!=null)
					{
						mySpinnerAdapter_Base = new MySpinnerAdapter(context, jsonArray_Base);
						spn_BASE_NAME.setAdapter(mySpinnerAdapter_Base);
						spn_BASE_NAME.setOnItemSelectedListener(new OnItemSelectedListener()
						{
							@Override
							public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
							{
								str_BASE_NAME = ((TextView)view.findViewById(R.id.tv_id)).getText().toString().trim();
							}
							@Override public void onNothingSelected(AdapterView<?> parent) { }
						});
					}
				}
				catch(JSONException e)
				{
					e.printStackTrace();
				}
			}
		});
	}

	private void set_State_Spinner_Value(JSONArray jsonArray_State, Spinner spinner, Context context2)
	{
		if(jsonArray_State!=null  && spinner!=null)
		{
			MySpinnerAdapter mySpinnerAdapter_State = new MySpinnerAdapter(context2, jsonArray_State);
			spinner.setAdapter(mySpinnerAdapter_State);
		}
	}
	
	protected void set_State_Spinner_position(Spinner spinner, String strId)
	{
		if(spinner!=null)
		{
			for (int i = 0; i < spinner.getCount(); i++)
			{
				View view = spinner.getAdapter().getView(i, null, null);
				TextView tvId = view!=null?(TextView)view.findViewById(R.id.tv_id):null;
				if(tvId!=null && (""+tvId.getText()).toString().trim().equalsIgnoreCase(strId))
				{
					spinner.setSelection(i);
					i=spinner.getCount();
				}
			}
		}
	}

	@Override
	public void onClick(View view)
	{
		switch (view.getId())
		{
			case R.id.fLayout_Profile_Pict:
				try
				{
					Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					intent.setType("image/*");
					startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
				}
				catch (ActivityNotFoundException anfe)
				{
					Toast.makeText(context, "Whoops - your device doesn't support capturing images!", Toast.LENGTH_LONG).show();
				}

				break;
			case R.id.btn_Update_Profile:
				update_profile();
				break;
	
			default:
				break;
		}
	}

	private void update_profile()
	{
		try
		{
			str_FIRST_NAME = et_FIRST_NAME.getText().toString().trim();
			str_LAST_NAME = et_LAST_NAME.getText().toString().trim();
			str_PHONE_NUMBER = et_PHONE_NUMBER.getText().toString().trim();
			str_ADDRESS = et_ADDRESS.getText().toString().trim();
			str_CITY = et_CITY.getText().toString().trim();
			str_ZIP_CODE = et_ZIP_CODE.getText().toString().trim();
			str_USER_NAME = et_USER_NAME.getText().toString().trim();
			str_EMAIL_ADDRESS = et_EMAIL_ADDRESS.getText().toString().trim();
			str_PASSWORD = et_PASSWORD.getText().toString().trim();
			str_TLC_NUMBER = et_TLC_NUMBER.getText().toString().trim();
			boolean isUser = MainActivity_Nutransit.strUserType.equalsIgnoreCase(TAG_user);
			if(!CommonCode.validateFirstName(str_FIRST_NAME))
				CommonCode.showEditTextErrorMessage(et_FIRST_NAME, resources.getString(R.string.Please_enter_the_valid_first_name));
			else if(!CommonCode.validateLastName(str_LAST_NAME))
				CommonCode.showEditTextErrorMessage(et_LAST_NAME, resources.getString(R.string.Please_enter_the_valid_last_name));
			else if(str_PHONE_NUMBER.length()<10 && isUser)
				CommonCode.showEditTextErrorMessage(et_PHONE_NUMBER, resources.getString(R.string.Please_enter_the_valid_phone_number));
			else if(str_USER_NAME.length()<2)
				CommonCode.showEditTextErrorMessage(et_USER_NAME, resources.getString(R.string.Please_enter_valid_user_name));
			else if(!CommonCode.isEmailValid(str_EMAIL_ADDRESS))
				CommonCode.showEditTextErrorMessage(et_EMAIL_ADDRESS, resources.getString(R.string.Please_enter_the_valid_email_id));
			else if(str_PASSWORD.length()<6)
				CommonCode.showEditTextErrorMessage(et_PASSWORD, resources.getString(R.string.Password_must_be_minimum_of_6_digits));
			else if(str_ADDRESS.length()<2 && !isUser)
				CommonCode.showEditTextErrorMessage(et_ADDRESS, resources.getString(R.string.Please_enter_address));
			else if(str_CITY.length()<2 && !isUser)
				CommonCode.showEditTextErrorMessage(et_CITY, resources.getString(R.string.Please_enter_valid_city));
			else if(str_ZIP_CODE.length()<6 && !isUser)
				CommonCode.showEditTextErrorMessage(et_ZIP_CODE, resources.getString(R.string.Please_enter_valid_zip_code));
			else if(str_TLC_NUMBER.length()<1 && !isUser)
				CommonCode.showEditTextErrorMessage(et_TLC_NUMBER, resources.getString(R.string.Please_enter_valid_TLC_number));
			else if(spn_DRIVER_TYPE.getSelectedItemPosition()==0 && !isUser)
				CommonCode.showMessage(resources.getString(R.string.Please_select_driver_type), context);
			else
			{
				str_DRIVER_TYPE = spn_DRIVER_TYPE.getSelectedItemPosition()==1?"c":"v";
				hashMap = new HashMap<String, String>();
				hashMap.put(TAG_userid, MainActivity_Nutransit.jsonObject_data.getString(TAG_id));
				hashMap.put(TAG_firstname, str_FIRST_NAME);
				hashMap.put(TAG_lastname, str_LAST_NAME);
				hashMap.put(TAG_username, str_USER_NAME);
				hashMap.put(TAG_password, str_PASSWORD);
				hashMap.put(TAG_email, str_EMAIL_ADDRESS);
				hashMap.put(TAG_flag, TAG_user);
				if(!isUser)
				{
					hashMap.put(TAG_flag, TAG_driver);
					hashMap.put(TAG_address, str_ADDRESS);
					hashMap.put(TAG_base, str_BASE_NAME);
					hashMap.put(TAG_dtype, str_DRIVER_TYPE);
					hashMap.put(TAG_tlc, str_TLC_NUMBER);
					hashMap.put(TAG_country, strCountry_id);
					hashMap.put(TAG_state, strStateId);
					hashMap.put(TAG_city, str_CITY);
					hashMap.put(TAG_zip, str_ZIP_CODE);
				}
				else
					hashMap.put(TAG_phno, str_PHONE_NUMBER);
				
				
				new AsyncTaskFileUploadUtility(context, hashMap, URL_UPDATE_PROFILE, imageFilePath!=null?new String[]{imageFilePath}:new String[]{}).getJSONResponse(new AsyncTaskInterface()
				{
					@Override
					public void getJSONObjectFromAsynkTask(JSONObject json)
					{
						try
						{
							if(json!=null)
							{
								if(json.has(TAG_message))
									CommonCode.showMessage(json.getString(TAG_message), context);
								if(json.has(TAG_status) && json.getString(TAG_status).equalsIgnoreCase(SUCCESS))
								{
									JSONObject jsonObject_data = json.getJSONArray(TAG_data).getJSONObject(0);
									MainActivity_Nutransit.jsonObject_data = jsonObject_data;
									sessionData.setString(TAG_data, ""+jsonObject_data);
									MainActivity_Nutransit.set_User_Data( ""+jsonObject_data, context);
									if(MainActivity_Nutransit.strUserType.equalsIgnoreCase(TAG_user))
										sessionData.setString(TAG_user_type, TAG_user);
									else
									{
										if(jsonObject_data.getString(TAG_driver_type).equalsIgnoreCase("c"))
											sessionData.setString(TAG_user_type, TAG_cab);
										else
											sessionData.setString(TAG_user_type, TAG_van);
									}
								}
							}
						}
						catch (JSONException e)
						{
							e.printStackTrace();
						}
					}
				});
			}
		}
		catch(JSONException e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == ActionBarActivity.RESULT_OK)
		{
			Uri uri = data.getData();
	        if (uri != null) 
	        {
	            Cursor cursor = context.getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
	            cursor.moveToFirst();
	            imageFilePath = cursor.getString(0);
	            if(imageFilePath!=null)
	            	iv_Profile_Pict.setImageURI(Uri.parse(imageFilePath));
	        }
		}
	}
	
}
